import { apiHost } from '@/config'
import { Http } from 'wdk'
import { toast } from 'vue-sdk'

/**
 * request with common settings
 * @param {Object} options
 * @param {Number} options.showWaiting 1: normal, 2: blocking
 * @param {Object} options.data The data to send, will stringify for Object
 */
function request (options) {
  options = Object.assign({
    showWaiting: 1
  }, options, {
    // set host for all requests
    url: apiHost + options.url,
    // for cors authentication
    withCredentials: true,
    timeout: 10e3,

    onTimeout () {
      toast.show({ message: '请求超时' })
    },
    onError () {
      toast.show({ message: '网络不给力' })
    }
  })

  // if (typeof options.data === 'object') {
  //   options.headers = Object.assign({}, options.headers, {
  //     // Setting the Content-Type suppresses the request to be simple
  //     // 'Content-Type': 'application/json; charset=utf-8'

  //     // To avoid the pre-flight, meet the simple requests conditions
  //     // server will handle Content-Language as Content-Type
  //     'Content-Language': 'json'
  //   })
  //   options.data = JSON.stringify(options.data)
  // }

  if (options.showWaiting) {
    toast.show({
      message: '加载中...',
      icon: 'loading',
      mask: options.showWaiting > 1,
      duration: options.timeout
    })
  }

  return new Http(options).then(req => {
    let { status, data } = req

    // success
    //
    if (status < 400) {
      toast.hide()
      return data
    }

    // fail
    //
    let errMsg = ''
    if (status === 401) {
      errMsg = '请先登录'
    } else if (status === 400) {
      errMsg = req.responseText
    } else {
      errMsg = '请求出错'
    }

    toast.show({ message: errMsg })
    return Promise.reject(req)
  }).send()
}

export default request
export function get (api, params, options) {
  return request(Object.assign({
    method: 'get',
    url: api,
    params
  }, options))
}
export function post (api, data, options) {
  return request(Object.assign({
    method: 'post',
    url: api,
    data
  }, options))
}
